package com.hc.api.controller;

import com.hc.api.enums.LoginTypeEnum;
import com.hc.api.utils.ApiUtil;
import com.hc.api.utils.TokenUtils;
import com.hc.comm.base.BaseController;
import com.hc.comm.dto.UserdataDTO;
import com.hc.comm.utils.*;
import com.hc.comm.vo.UserdataVO;
import com.hc.service.model.LoginInfoModel;
import com.hc.service.model.UserdataModel;
import com.hc.service.service.ILoginInfoService;
import com.hc.service.service.IUserdataService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by yx on 2017/3/30.
 */
@Controller
@Scope("prototype")
@RequestMapping("/" + ApiUtil.ApiVersion.V1 + "/user/")
public class YGRebateController extends BaseController {

    @Resource(name = "userdataService")
    private IUserdataService userdataService;

    @Resource(name = "loginInfoService")
    private ILoginInfoService loginInfoService;

    @ResponseBody
    @RequestMapping("register")
    public void register(HttpServletRequest request, HttpServletResponse response, @ModelAttribute UserdataDTO userdataDTO) throws Exception {
        //response.setContentType(ContentTypeEnum.TEXT_JSON.getValue());
        if (userdataDTO == null || userdataDTO.getUnionId().isEmpty()) {
            ExceptionUtils.outputMessage(response, Integer.valueOf(Constant.ResultEnum.ERROR.getResult()), "登录失败！");
            return;
        }
        UserdataModel model = userdataService.getOne(userdataDTO);

        UserdataVO userdataVO = new UserdataVO();
        userdataVO.copyPropertis(model);
        String[] params = {"deviceId", "telephone", "appToken"};
        JsonUtils.toSuccessResult(request, response, userdataVO, params);
    }

    /**
     * login_type  登录类型 0：手机号码注册，1：微信注册登录，2:注册登录
     * union_id   第三方登录union_id
     * app_chanal 渠道
     * device_type  设备的类型
     * device_id    手机的设备号
     *
     * @param request
     * @throws Exception
     */
    @RequestMapping("yglogin")
    public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("登录====yglogin");
       // JsonUtils.getJsonpFunctionName(request);
        String login_type = request.getParameter("login_type");
        String union_id = request.getParameter("union_id");
        String portrait = request.getParameter("portrait");
        String user_name = request.getParameter("user_name");
        String app_chanal = request.getParameter("app_chanal");
        String device_type = request.getParameter("device_type");
        // String access_token = request.getParameter("access_token");
        String device_id = request.getParameter("device_id");
        System.out.println(login_type);
        System.out.println(union_id);
//        Enumeration enums =request.getHeaderNames();
//      while (enums.hasMoreElements()){
//          Object key = enums.nextElement();
//          System.out.println(key+":"+request.getHeader(key.toString()));
//      }
//        System.out.println(JsonUtils.toJSONString(request.getParameterMap(),true));

        if (StringUtil.isEmpty(login_type) || StringUtil.isEmpty(union_id)
                || StringUtil.isEmpty(device_id)) {
            //writeToJson("参数不完整！");
            JsonUtils.toErrorResult(request, response, "参数不完整！");
            return;
        }
        UserdataDTO userdataDTO = new UserdataDTO();
        userdataDTO.setUnionId(union_id);
        UserdataModel model = userdataService.getOne(userdataDTO);

        if (model == null) {
            System.out.println("增加用戶~");
            model = new UserdataModel();
            model.setUnionId(union_id);
            model.setLoginType(Integer.valueOf(login_type));
            model.setUserName(user_name);
            model.setPortrait(portrait);
            model.setAppChannel(app_chanal);
            model.setCreateTime(System.currentTimeMillis() / 1000);
            model.setRegistDeviceType(device_type);
            model.setDeviceId(device_id);
            String salt = StringUtil.getStringRandom(3);
            model.setSalt(salt);
            //增加一个新用户
            model = userdataService.insert(model);
            //生成一条登录记录
            LoginInfoModel loginInfoModel = new LoginInfoModel();
            loginInfoModel.setCreateTime(System.currentTimeMillis() / 1000);
            loginInfoModel.setClient(device_type);
            loginInfoModel.setUserId(model.getId());
            loginInfoModel.setIp(request.getRemoteAddr());
            loginInfoModel.setDeviceId(device_id);
            loginInfoModel = loginInfoService.insert(loginInfoModel);
            //再生成用户的token
            String newToken = TokenUtils.generateAccessToken(model.getId());
            if (loginInfoModel != null && !StringUtil.isEmpty(newToken)) {
                model.setAppToken(newToken);
                userdataService.updateByPrimaryKey(model);
                System.out.println("salt:" + model.getSalt());
                System.out.println("access_token:" + newToken);
            } else {
                ExceptionUtils.outputMessage(response, Integer.valueOf(Constant.ResultEnum.ERROR.getResult()), "注册失败");
            }

        } else {
            System.out.println("用戶登錄~");
            //生成用户的登录记录
            LoginInfoModel loginInfoModel = new LoginInfoModel();
            loginInfoModel.setCreateTime(System.currentTimeMillis() / 1000);
            loginInfoModel.setClient(device_type);
            loginInfoModel.setUserId(model.getId());
            loginInfoModel.setIp(request.getRemoteAddr());
            loginInfoModel.setDeviceId(device_id);
            loginInfoModel = loginInfoService.insert(loginInfoModel);
            //更新用户的token
            String newToken = TokenUtils.generateAccessToken(model.getId());
            System.out.println("access_token:" + newToken);
            if (loginInfoModel != null && !StringUtil.isEmpty(newToken)) {
                model.setAppToken(newToken);
                userdataService.updateByPrimaryKey(model);
            } else {
                ExceptionUtils.outputMessage(response, Integer.valueOf(Constant.ResultEnum.ERROR.getResult()), "登录失败！");
            }
        }
        // JsonUtils.toSuccessResult(request, response, userdataVO, params);
        JsonUtils.toSuccessResult(request, response, model, "id", "userName", "nickName", "status", "portrait", "telephone", "appToken");
        // writeToJson(UserInfoUtil.getAppUserInfo(model));
    }

    /**
     * 请求验证码
     *
     * @param request
     * @param response
     * @param userdataDTO
     * @throws Exception
     */
    @RequestMapping("register/tel1")
    public void registerForTelephone(HttpServletRequest request, HttpServletResponse response, UserdataDTO userdataDTO) throws Exception {
        if (userdataDTO == null || StringUtil.isEmpty(userdataDTO.getTelephone())) {
            JsonUtils.toErrorResult(request, response, "參數錯誤");
            return;
        }
        if (!StringUtil.isPhone(userdataDTO.getTelephone())) {
            JsonUtils.toErrorResult(request, response, "请输入电话号码");
        } else {
            JsonUtils.toSuccessResult(request, response, "发送短信验证码成功！");
        }
        //TODO 请求验证码
    }

    /**
     * msgCode 验证验证码
     * 需要手机号，密码，验证码
     * 设备号
     * registDeviceType 设备类型
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("register/tel2")
    public void registerForTelePhoneTwo(HttpServletRequest request, HttpServletResponse response, UserdataDTO userdataDTO) throws Exception {
        String msgCode = request.getParameter("msgCode");
        if (StringUtil.isEmpty(msgCode) || userdataDTO == null
                || StringUtil.isEmpty(userdataDTO.getTelephone())
                || !StringUtil.isPhone(userdataDTO.getTelephone())
                || StringUtil.isEmpty(userdataDTO.getPassword())
                || StringUtil.isEmpty(userdataDTO.getDeviceId())) {
            JsonUtils.toErrorResult(request, response, "參數錯誤");
        } else if (msgCode.equals("123456")) {
            String salt = StringUtil.getStringRandom(3);
            userdataDTO.setSalt(salt);
            UserdataModel userdataModel = new UserdataModel();
            userdataDTO.setSalt(salt);
            userdataModel.setTelephone(userdataDTO.getTelephone());
            userdataModel.setDeviceId(userdataDTO.getDeviceId());
            userdataModel.setCreateTime(System.currentTimeMillis() / 1000);
            userdataModel.setRegistDeviceType(userdataDTO.getRegistDeviceType());
            //登录方式
            userdataModel.setLoginType(LoginTypeEnum.TELEPHONE.getCode());
            //密码md5
            userdataModel.setPassword(SecurityUtils.md5(userdataDTO.getPassword() + salt));
            userdataModel = userdataService.insert(userdataModel);
            userdataModel.setUpdateTime(System.currentTimeMillis() / 1000);
            userdataModel.setAppToken(TokenUtils.generateAccessToken(userdataModel.getId()));
            try {
                userdataService.updateByPrimaryKey(userdataModel);
                LoginInfoModel loginInfoModel = new LoginInfoModel();
                loginInfoModel.setUserId(userdataModel.getId());
                loginInfoModel.setDeviceId(userdataModel.getDeviceId());
                loginInfoModel.setCreateTime(System.currentTimeMillis() / 1000);
                loginInfoModel.setClient(userdataModel.getRegistDeviceType());
                loginInfoModel.setUpdateTime(System.currentTimeMillis() / 1000);
                loginInfoService.insert(loginInfoModel);
                JsonUtils.toSuccessResult(request, response, userdataModel, "注册成功！",
                        "id", "userName", "nickName", "status", "portrait", "telephone", "appToken");
            } catch (Exception e) {
                JsonUtils.toErrorResult(request, response, "注册失败！");
            }
        }
    }


}
